package com.ewins.weatherdataclient.ui;

import com.ewins.weatherdataclient.common.Constant;
import com.google.common.eventbus.EventBus;
import org.apache.log4j.Logger;

import java.net.HttpURLConnection;
import java.net.SocketException;
import java.net.URL;

/**
 * Created by anzilu on 2016/3/7.
 */
public class NetWorkMonitor implements Runnable{

    URL urlobject;
    HttpURLConnection connection;
    int responseCode;       //服务器返回值
    EventBus eb;
    boolean beMonitored;
    Logger logger=Logger.getLogger(NetWorkMonitor.class);

    public NetWorkMonitor(EventBus eb){

        this.eb=eb;

    }
    @Override
    public void run() {

        beMonitored=true;
        while(beMonitored) {
            try {
                //HttpsDefault.setDefaultValue();
                urlobject = new URL(Constant.DownLoadCatalogUrl);
                connection = (HttpURLConnection) urlobject.openConnection();
                //connection.setSSLSocketFactory(HttpsDefault.getSSLSocketFactory());
                connection.connect();
                responseCode = connection.getResponseCode();
                //0: normal,1:unnormal
                if (responseCode == 200) {
                    eb.post("0");
                }
                if (responseCode == 404 || responseCode >= 500) {
                    eb.post("1");
                }
                else {
                    eb.post("0");
                }
                connection.disconnect();
            }
            catch (SocketException e) {
                eb.post("1");
                logger.error("网络监控异常：" + e.getMessage());
            }
            catch (Exception e) {
                eb.post("1");
                logger.error("网络监控异常：" + e.getMessage());
            }
            try {
                Thread.sleep(5000);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
